package com.hy.ximalaya.controller;

import com.alibaba.fastjson.JSONArray;
import com.hy.common.HttpUtils;
import com.hy.ximalaya.entity.Track;
import com.hy.ximalaya.service.Ximalaya;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author hy 2327401139@qq.com
 * @version 1.0 2021/2/3 23:17
 */
@Controller
@RequestMapping("/ximalaya")
public class XimalayaController {

    /**
     * 下载全量的book到本地
     */
    @GetMapping("/down/{albumId}/full")
    public void downloadFull(@PathVariable String albumId, HttpServletResponse response, HttpServletRequest request) throws Exception {

        response.reset();

        //设置响应编码格式
        response.setCharacterEncoding("UTF-8");
        //设置报文格式，告诉浏览器要做下载
        //response.setContentType("application/x-download");
        response.setContentType("multipart/form-data");

        //构建一个ximalaya
        Ximalaya ximalaya = new Ximalaya();
        ximalaya.setAlbumId(Integer.valueOf(albumId));
        List<Track> tracks = ximalaya.sendRequest();

        //设置压缩包的名字
        //解决不同浏览器压缩包名字含有中文时乱码的问题
        String downloadName = resolve(request, ximalaya.getAlbum().getTitle(), ".zip");

        //弹出下载文件对话框
        response.addHeader("Content-Disposition", "attachment;filename=\"" + downloadName + "\"");

        //设置压缩流：直接写入response，实现边压缩边下载
        ZipOutputStream zipOS = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
        zipOS.setMethod(ZipOutputStream.DEFLATED);

        //循环将文件写入压缩流
        for (Track track : tracks) {
            System.out.println("正在获取：" + track.getTitle());
            byte[] bytes = HttpUtils.sendRequest(new URL(track.getPlayUrl64())).bodyAsBytes();
            //添加ZipEntry，并ZipEntry中写入文件流
            zipOS.putNextEntry(new ZipEntry(track.getTitle() + ".mp3"));
            zipOS.write(bytes);
            zipOS.closeEntry();
        }

        System.out.println(ximalaya.getAlbum().getTitle() + "获取完成,开始下载....");

        zipOS.close();

    }

    /**
     * 获取book的下载地址.txt到本地
     */
    @GetMapping("/down/{albumId}/links")
    public void downloadLinkTxt(@PathVariable String albumId,HttpServletResponse response, HttpServletRequest request) throws Exception {

        response.reset();

        //设置响应编码格式
        response.setCharacterEncoding("UTF-8");
        //设置报文格式，告诉浏览器要做下载
        //response.setContentType("application/x-download");
        response.setContentType("multipart/form-data");

        //构建Ximalay获取下载链接
        Ximalaya ximalaya = new Ximalaya();
        ximalaya.setAlbumId(Integer.valueOf(albumId));
        List<Track> tracks = ximalaya.sendRequest();

        //将下载链接保存到StringBuilder
        StringBuilder sb = new StringBuilder();
        tracks.forEach(track -> sb.append(track.getPlayUrl64()).append("\n"));

        //获取书名
        String bookName = resolve(request, ximalaya.getAlbum().getTitle(), ".txt");

        //弹出下载文件对话框开始下载文件
        response.addHeader("Content-Disposition", "attachment;filename=\"" + bookName + "\"");
        response.getOutputStream().write(sb.toString().getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 解决不同浏览器文件名字含有中文时乱码的问题
     *
     * @param request    controller发来的request
     * @param name       文件名称
     * @param suffixName 文件后缀，没有则传 null
     */
    private String resolve(HttpServletRequest request, String name, String suffixName){

        String agent = request.getHeader("USER-AGENT");

        if (suffixName != null) {
            name += suffixName;
        }

        try {
            if (agent.contains("MSIE") || agent.contains("Trident")) {
                name = java.net.URLEncoder.encode(name, "UTF-8");
            } else {
                name = new String(name.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return name;
    }

    /**
     * 获取book下载地址Json
     */
    @GetMapping("/api/{albumId}/links")
    @ResponseBody
    public String getDownloadLinkJson(@PathVariable String albumId) throws Exception {
        Ximalaya ximalaya = new Ximalaya();
        ximalaya.setAlbumId(Integer.valueOf(albumId));
        List<Track> tracks = ximalaya.sendRequest();
        return JSONArray.toJSONString(tracks);
    }
}
